package com.jsu.clubmanagementsystem.service.club.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsu.clubmanagementsystem.common.ErrorCode;
import com.jsu.clubmanagementsystem.common.PageQueryRequest;
import com.jsu.clubmanagementsystem.common.ResultUtils;
import com.jsu.clubmanagementsystem.constant.CommonConstant;
import com.jsu.clubmanagementsystem.constant.UserConstant;
import com.jsu.clubmanagementsystem.mapper.UserMapper;
import com.jsu.clubmanagementsystem.model.dto.review.AcceptApplicationRequest;
import com.jsu.clubmanagementsystem.exception.BusinessException;
import com.jsu.clubmanagementsystem.model.dto.club.ClubAddRequest;
import com.jsu.clubmanagementsystem.model.dto.club.ClubDeleteRequest;
import com.jsu.clubmanagementsystem.model.dto.club.ClubQueryRequest;
import com.jsu.clubmanagementsystem.model.dto.club.ClubUpdateRequest;
import com.jsu.clubmanagementsystem.model.dto.clubmembership.ClubMemberQueryRequest;
import com.jsu.clubmanagementsystem.model.entity.*;
import com.jsu.clubmanagementsystem.model.enums.ActivityStatusEnum;
import com.jsu.clubmanagementsystem.model.enums.ClubMemberRoleEnum;
import com.jsu.clubmanagementsystem.model.enums.ReviewResultEnum;
import com.jsu.clubmanagementsystem.mapper.ClubMapper;
import com.jsu.clubmanagementsystem.model.vo.club.ClubMembershipVO;
import com.jsu.clubmanagementsystem.model.vo.club.ClubTypeVO;
import com.jsu.clubmanagementsystem.model.vo.club.ClubVO;
import com.jsu.clubmanagementsystem.model.vo.club.ListClubVO;
import com.jsu.clubmanagementsystem.model.vo.clubAnnouncement.ClubAnnouncementVO;
import com.jsu.clubmanagementsystem.model.vo.user.UserVO;
import com.jsu.clubmanagementsystem.service.activity.ActivityMembershipService;
import com.jsu.clubmanagementsystem.service.activity.ActivityService;
import com.jsu.clubmanagementsystem.service.application.ClubApplicationService;
import com.jsu.clubmanagementsystem.service.club.ClubAnnouncementService;
import com.jsu.clubmanagementsystem.service.club.ClubMembershipService;
import com.jsu.clubmanagementsystem.service.club.ClubService;
import com.jsu.clubmanagementsystem.service.user.UserService;
import com.jsu.clubmanagementsystem.utils.SqlUtils;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 24753
* @description 针对表【club(社团)】的数据库操作Service实现
* @createDate 2025-05-13 17:19:16
*/
@Service
public class ClubServiceImpl extends ServiceImpl<ClubMapper, Club>
        implements ClubService {

    @Resource
    private UserService userService;

    @Resource
    @Lazy
    private UserMapper userMapper;

    @Resource
    private ClubAnnouncementService announcementService;

    @Resource
    private ClubMembershipService membershipService;

    @Resource
    @Lazy
    private ActivityService activityService;

    @Resource
    @Lazy
    private ActivityMembershipService activityMembershipService;

    @Resource
    @Lazy
    private ClubApplicationService applicationService;

    /**
     * 增加社团 调用
     * @param addRequest
     * @return
     */
    @Override
    public long addClub(ClubAddRequest addRequest) {
        Club club = new Club();
        BeanUtils.copyProperties(addRequest, club);
        club.setTags(JSONUtil.toJsonStr(addRequest.getTags()));
        club.setMemberCount(0);
        clubValidation(club, true);
        addClubValidation(club);

        return this.addClub1(club);
    }

    /**
     * 增加社团 实现
     *
     * @param club
     * @return
     */
    @Transactional
    protected long addClub1(Club club) {
        if (!this.save(club)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加失败");
        }

        //绑定用户的manageClubId
        User user = userService.getById(club.getUserId());
        user.setUserRole("manager");
        user.setManagedClubId(club.getId());
        userService.updateById(user);

        //更新membership
        ClubMembership membership = new ClubMembership();
        membership.setUserId(club.getUserId());
        membership.setClubId(club.getId());
        membership.setIdentity("manager");
        if ( !this.addMemberToClub(membership)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新成员关系失败");
        }
        return club.getId();
    }

    /**
     * 删除社团 调用
     *
     * @param club
     * @return
     */
    @Transactional
    public boolean deleteClub(Club club) {
        return this.deleteClub1(club);
    }

    /**
     * 删除社团 实现
     *
     * @param club
     * @return
     */
    public boolean deleteClub1(Club club) {
        Long clubId = club.getId();
        Long userId = club.getUserId();
        Long announcementId = club.getAnnouncementId();

        // 删除成员关系记录
        QueryWrapper<ClubMembership> clubMembershipQueryWrapper = new QueryWrapper<>();
        clubMembershipQueryWrapper.eq("clubId", clubId);
        if (membershipService.count(clubMembershipQueryWrapper) > 0 &&
                !membershipService.remove(clubMembershipQueryWrapper)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "删除成员关系记录失败");
        }
        // 公告失效
        if (announcementId != null && announcementService.getById(announcementId) != null) {
            if (!announcementService.removeById(announcementId)) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "修改公告失败");
            }
        }
        // 标记已注销状态
        if (!this.removeById(clubId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "注销社团失败");
        }
        // 修改社长身份
        User oldManager = userService.getById(userId);
        oldManager.setManagedClubId(0L);
        oldManager.setUserRole(UserConstant.USER_ROLE_USER);
        if (!userService.updateById(oldManager)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "修改社长信息失败");
        }
        return true;
    }

    /**
     * 更改社团信息 调用
     * @param updateRequest
     * @return
     */
    @Override
    public boolean updateClub(ClubUpdateRequest updateRequest) {
        Long clubId = updateRequest.getId();
        Club oldClub = this.getById(clubId);
        if (oldClub == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "请求社团不存在");
        }
        Long newManagerId = updateRequest.getUserId();
        if (newManagerId != null && !newManagerId.equals(oldClub.getUserId())){
            updateManagerValidation(newManagerId, clubId);
        }

        Club newClub = new Club();
        BeanUtils.copyProperties(updateRequest, newClub);
        newClub.setTags(JSONUtil.toJsonStr(updateRequest.getTags()));
        clubValidation(newClub, false);
        return this.updateClub1(newClub);
    }

    /**
     * 更改社团信息 实现
     *
     * @param newClub
     * @return
     */
    @Transactional
    protected boolean updateClub1(Club newClub) {
        Club oldClub = this.getById(newClub.getId());
        if (!this.updateById(newClub)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新社团信息失败");
        }

        Long newManagerId = newClub.getUserId();
        Long oldManagerId = oldClub.getUserId();
        if (newManagerId != null && !newManagerId.equals(oldClub.getUserId())){
            this.updateManager(newManagerId, oldManagerId);
        }
        return true;
    }

    /**
     * 更改社团的社长
     * @param newManagerId
     * @param oldManagerId
     * @return
     */
    @Override
    public void updateManager(Long newManagerId, Long oldManagerId) {
        User oldManager = userService.getById(oldManagerId);
        User newManager = userService.getById(newManagerId);
        Long clubId = oldManager.getManagedClubId();

        QueryWrapper<ClubMembership> newQueryWrapper = membershipService.getQueryWrapper(newManagerId, clubId);
        ClubMembership newMembership = membershipService.getOne(newQueryWrapper);
        newMembership.setIdentity(ClubMemberRoleEnum.MANAGER.getInfo());
        newManager.setUserRole(UserConstant.USER_ROLE_MANAGER);
        newManager.setManagedClubId(oldManager.getManagedClubId());
        if (!userService.updateById(newManager)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新新社长信息失败");
        }
        if (!membershipService.updateById(newMembership)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新新社长信息失败");
        }

        QueryWrapper<ClubMembership> oldQueryWrapper = membershipService.getQueryWrapper(oldManagerId, oldManager.getManagedClubId());
        ClubMembership oldMembership = membershipService.getOne(oldQueryWrapper);
        oldMembership.setIdentity(ClubMemberRoleEnum.MEMBER.getInfo());
        oldManager.setUserRole(UserConstant.USER_ROLE_USER);
        oldManager.setManagedClubId(0L);
        if (!userService.updateById(oldManager)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新前社长信息失败");
        }
        if (!membershipService.updateById(oldMembership)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新前社长信息失败");
        }
    }

    /**
     * 更新公告
     * @param announcement
     * @return
     */
    @Override
    @Transactional
    public Long updateAnnouncement(ClubAnnouncement announcement) {
        announcementService.validateAnnouncement(announcement);
        //如果社团不存在
        Long clubId = announcement.getClubId();
        Club club = this.getById(clubId);
        if (club == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "目标社团不存在");
        }

        //把过往的公告改成已过时
        ClubAnnouncement oldAnnouncement = announcementService.getById(club.getAnnouncementId());
        if (oldAnnouncement != null) {
            announcementService.removeById(oldAnnouncement.getId());
        }
        //插入
        if (!announcementService.save(announcement)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "插入失败");
        }
        //更新目标社团当前有效公告
        club.setAnnouncementId(announcement.getId());
        if (!this.updateById(club)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "更新社团公告失败");
        }
        return announcement.getId();
    }

    /**
     * 添加成员到社团
     *
     * @param membership 社团成员关系
     * @return 添加结果
     */
    @Override
    public boolean addMemberToClub(ClubMembership membership) {
        this.addMemberToClubValidation(membership);
        Club club = this.getById(membership.getClubId());
        Club updatedClub = new Club();
        updatedClub.setId(club.getId());
        updatedClub.setMemberCount(club.getMemberCount() + 1);
        if (!this.updateById(updatedClub)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "修改社团人数失败");
        }
        return membershipService.save(membership) ;
    }

    /**
     * 删除成员
     * @param membership
     * @param isDeleteClub
     * @return
     */
    @Override
    public boolean deleteMemberFromClub(ClubMembership membership, boolean isDeleteClub) {
        if(membership == null){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        this.deleteMemberFromClubValidation(membership, isDeleteClub);
        Long userId = membership.getUserId();
        Long clubId = membership.getClubId();
        QueryWrapper<ClubMembership> queryWrapper = membershipService.getQueryWrapper(userId, clubId);
        ClubMembership existMembership = membershipService.getOne(queryWrapper);

        Club updatedClub = new Club();
        Club club = this.getById(membership.getClubId());
        updatedClub.setId(club.getId());
        updatedClub.setMemberCount(club.getMemberCount() - 1);
        if (!this.updateById(updatedClub)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "修改社团人数失败");
        }
        return membershipService.removeById(existMembership);
    }

    /**
     * 获取封装对象
     * @param club
     * @return
     */
    @Override
    public ClubVO getClubVO(Club club) {
        if(club == null){
            return null;
        }

        ClubVO clubVO = ClubVO.objToVo(club);
        //处理社团公告vo
        ClubAnnouncement announcement = announcementService.getById(club.getAnnouncementId());
        if(announcement != null)
            clubVO.setClubAnnouncementVo(ClubAnnouncementVO.objToVo(announcement));
        //处理UserVo
        User user = userService.getById(club.getUserId());
        if (user == null) {
            ResultUtils.error(ErrorCode.NOT_FOUND);
        }
        UserVO userVO = UserVO.objToVoLessInfo(user);
        clubVO.setUserVO(userVO);
        return clubVO;
    }

    /**
     * 获取封装对象
     *
     * @param clubMembership
     * @return
     */
    @Override
    public ClubMembershipVO getClubMembershipVo(ClubMembership clubMembership) {
        User user = userService.getById(clubMembership.getUserId());
        UserVO userVO = UserVO.objToVoAllInfo(user);
        Club club = this.getById(clubMembership.getClubId());
        ClubVO clubVO = this.getClubVO(club);
        String identity = clubMembership.getIdentity();

        ClubMembershipVO clubMembershipVO = new ClubMembershipVO();
        clubMembershipVO.setUserVO(userVO);
        clubMembershipVO.setClubVO(clubVO);
        clubMembershipVO.setIdentity(identity);
        return clubMembershipVO;
    }

    /**
     * 获取封装对象 (分页)
     * @param page
     * @return
     */
    @Override
    public Page<ClubVO> getClubVoPage(Page<Club> page) {
        List<Club> clubList = page.getRecords();
        Page<ClubVO> clubVOPage = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        //判空，为空返回空页
        if (CollUtil.isEmpty(clubList)) {
            return clubVOPage;
        }
        //处理封装
        List<ClubVO> clubVOList = clubList.stream()
                .map(club -> {
                    return this.getClubVO(club);
                })
                .collect(Collectors.toList());
        clubVOPage.setRecords(clubVOList);
        return clubVOPage;
    }

    /**
     * 查看用户所加入的社团
     * @param queryRequest
     * @return
     */
    public Page<ClubMembershipVO> listClubMembershipVoOfUserByPage(ClubMemberQueryRequest queryRequest) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        Long userId = queryRequest.getUserId();
        if ( !userService.isExist(userId)) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户不存在");
        }

        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        QueryWrapper<ClubMembership> queryWrapper = membershipService.getQueryWrapper(userId, 0L);
        List<ClubMembershipVO> clubMembershipVOList = membershipService.list(queryWrapper).stream()
                .map(clubMembership -> { return this.getClubMembershipVo(clubMembership); })
                .collect(Collectors.toList());

        Page<ClubMembershipVO> clubMembershipVOPage = new Page<>(current, pageSize);
        clubMembershipVOPage.setRecords(clubMembershipVOList);
        return clubMembershipVOPage;
    }

    /**
     * 查看社团成员表 (未封装、分页)
     * @param queryRequest 查询请求
     * @return
     */
    @Override
    public Page<ClubMembershipVO> listClubMembershipVoOfClubByPage(ClubMemberQueryRequest queryRequest) {
        if (queryRequest == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        Long clubId = queryRequest.getClubId();
        if ( !this.isExist(clubId)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "社团不存在");
        }

        int current = queryRequest.getCurrent();
        int pageSize = queryRequest.getPageSize();
        QueryWrapper<ClubMembership> membershipQueryWrapper = membershipService.getQueryWrapper(0L, clubId);

        // 如果有用户名、专业或年级筛选，需要关联User表进行查询
        String userName = queryRequest.getUserName();
        String major = queryRequest.getMajor();
        String grade = queryRequest.getGrade();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like(StringUtils.isNotBlank(userName), "userName", userName);
        userQueryWrapper.eq(StringUtils.isNotBlank(major), "major", major);
        userQueryWrapper.eq(StringUtils.isNotBlank(grade), "grade", grade);

        List<Long> userIdList = userService.list(userQueryWrapper).stream().map(User::getId).collect(Collectors.toList());
        membershipQueryWrapper.in(!userIdList.isEmpty(), "userId", userIdList);
        List<ClubMembershipVO> clubMembershipVOList = membershipService.list(membershipQueryWrapper).stream()
                .map(clubMembership -> { return this.getClubMembershipVo(clubMembership); })
                .collect(Collectors.toList());
        Page<ClubMembershipVO> page = new Page<>(current, pageSize);
        page.setRecords(clubMembershipVOList);
        return page;
    }

    /**
     * 获取查询封装
     * @param queryRequest
     * @return
     */
    @Override
    public QueryWrapper<Club> getQueryWrapper(ClubQueryRequest queryRequest) {
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        if (queryRequest == null)
            return queryWrapper;

        Long id = queryRequest.getId();
        String clubName = queryRequest.getClubName();
        List<String> tags = queryRequest.getTags();
        String sortField = queryRequest.getSortField();
        String sortOrder = queryRequest.getSortOrder();

        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.like(StringUtils.isNotBlank(clubName), "clubName", clubName);
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取社团类别及其对应的社团数
     * @return
     */
    public HashMap<String, Integer> getClubTypeStatics(){
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        List<Club> clubList = this.list(queryWrapper);

        HashMap<String, Integer> clubTypeStatics = new HashMap<>();
        for(Club club : clubList){
            List<String> tagList = JSONUtil.toList(club.getTags(), String.class);
            String clubType = tagList.get(0);
            if (clubTypeStatics.containsKey(clubType)){
                clubTypeStatics.put(clubType, clubTypeStatics.get(clubType) + 1);
            } else {
                clubTypeStatics.put(clubType, 1);
            }
        }
        return clubTypeStatics;
    }

    /**
     * 社团是否存在
     *
     * @param clubId 社团id
     * @return
     */
    @Override
    public boolean isExist(Long clubId) {
        if (clubId == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        return this.getById(clubId) != null;
    }

    /**
     * 用户是否是该社团的社长
     *
     * @param userId 用户id
     * @param clubId 社团id
     * @return
     */
    @Override
    public boolean isManagerOfClub(Long userId, Long clubId) {
        User user = userService.getById(userId);
        if (!user.getUserRole().equals(UserConstant.USER_ROLE_MANAGER)) {
            return false;
        }
        return user.getManagedClubId().equals(clubId);
    }

    /**
     * 用户是否已是其他社团的社长
     *
     * @param userId 用户id
     * @param clubId 社团id
     */
    @Override
    public boolean isManagerOfOtherClub(Long userId, Long clubId) {
        User user = userService.getById(userId);
        Long userManagedClubId = user.getManagedClubId();
        return (userManagedClubId != null && userManagedClubId > 0 && !userManagedClubId.equals(clubId));
    }

    /**
     * 校验club参数格式
     * @param club 社团对象
     */
    @Override
    public void clubValidation(Club club, boolean isAdd) {
        if (club == null) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }

        String clubName = club.getClubName();
        String tags = club.getTags();
        String introduction = club.getIntroduction();

        if (StringUtils.isNotBlank(tags)) {
            clubTagsValidation(tags);
        }
        if (isAdd) {
            clubNameValidation(clubName);
            clubIntroductionValidation(introduction);
            return;
        }

        Club originClub = this.getById(club.getId());
        if (StringUtils.isNotBlank(clubName) && !originClub.getClubName().equals(clubName)) {
            clubNameValidation(clubName);
        }
        if (StringUtils.isNotBlank(introduction) && !originClub.getIntroduction().equals(introduction)) {
            clubIntroductionValidation(introduction);
        }
    }

    /**
     * 社团名校验
     *
     * @param clubName
     */
    private void clubNameValidation(String clubName) {
        if (StringUtils.isBlank(clubName)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "社团名为空");
        }
        if (clubName.length() > 20) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "社团名过长");
        }

        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clubName", clubName);
        if (this.count(queryWrapper) > 0) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "该社团名已被使用");
        }
    }

    /**
     * 社团简介校验
     * @param introduction
     */
    private void clubIntroductionValidation(String introduction) {
        if (StringUtils.isBlank(introduction)) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "社团简介为空");
        }
        if (introduction.length() > 1024) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "社团简介过长");
        } else if (introduction.length() < 5) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "社团简介过短");
        }
    }

    /**
     * 社团标签校验
     * @param tags
     */
    private void clubTagsValidation(String tags) {
        if (tags.length() > 512) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "分类标签过长");
        }
    }

    /**
     * 更换社长的安全校验
     * @param newManagerId
     * @param clubId
     */
    @Override
    public void updateManagerValidation(Long newManagerId, Long clubId){
        User newManager = userService.getById(newManagerId);
        if (newManager == null){
            throw new BusinessException(ErrorCode.NOT_FOUND, "指定新社长用户不存在");
        }
        if (newManager.getUserRole().equals(UserConstant.USER_ROLE_ADMIN)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "目标新社长为管理员，不可成为社长");
        }
        if (!membershipService.isMemberOfClub(newManagerId, clubId)){
            throw new BusinessException(ErrorCode.NOT_FOUND, "指定新社长用户不是该社团成员，不能直接成为社长");
        }
        Club club = this.getById(clubId);
        if (newManagerId.equals(club.getUserId())) {
            throw new BusinessException(ErrorCode.PARAM_ERROR, "新社长和前社长是同一人");
        }
        Long newManagerManagedClubId = newManager.getManagedClubId();
        if (newManagerManagedClubId != null && newManagerManagedClubId > 0 && !newManagerManagedClubId.equals(clubId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "目标新社长已是其他社团的社长");
        }
    }

    /**
     * 创建社团的安全验证
     *
     * @param club
     */
    @Override
    public void addClubValidation(Club club) {
        Long userId = club.getUserId();
        User user = userService.getById(club.getUserId());
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "目标用户不存在");
        }
        if (user.getUserRole().equals(UserConstant.USER_ROLE_MANAGER)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "目标用户已是社长，不可添加");
        } else if (user.getUserRole().equals(UserConstant.USER_ROLE_ADMIN)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "目标用户是管理员，不可添加");
        }
        if (!membershipService.isUserInLessThan3Club(userId)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户所加入社团已达到上限，无法创建社团");
        }
    }

    /**
     * 添加社团新成员的安全验证
     * @param membership
     */
    @Override
    public void addMemberToClubValidation(ClubMembership membership) {
        if(membership == null){
            throw new BusinessException(ErrorCode.PARAM_ERROR, "参数为空");
        }
        Long userId = membership.getUserId();
        Long clubId = membership.getClubId();
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "请求用户不存在");
        }
        if (user.getUserRole().equals(UserConstant.USER_ROLE_ADMIN)){
            throw new BusinessException(ErrorCode.NO_AUTH, "管理员无法加入社团");
        }
        if ( !this.isExist(clubId)) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "请求社团不存在");
        }

        QueryWrapper<ClubMembership> membershipQueryWrapper = membershipService.getQueryWrapper(userId, 0L);
        if (membershipService.count(membershipQueryWrapper) >= 3) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户无法同时加入多于三个社团");
        }
        membershipQueryWrapper.eq("clubId", clubId);
        if (membershipService.count(membershipQueryWrapper) > 0) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户已经加入此社团");
        }
        // 当直接添加用户为社长时
        if(membership.getIdentity().equals(ClubMemberRoleEnum.MANAGER.getInfo()) && this.isManagerOfOtherClub(userId, clubId)){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "该用户已经是其他社团的社长");
        }
    }

    /**
     * 移除社团成员的安全验证
     *
     * @param membership
     * @param isDeleteClub
     */
    @Override
    public void deleteMemberFromClubValidation(ClubMembership membership, boolean isDeleteClub) {
        Long userId = membership.getUserId();
        User user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "用户不存在");
        }
        Long clubId = membership.getClubId();
        Club club = this.getById(membership.getClubId());
        if (club == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND, "请求社团不存在");
        }
        QueryWrapper<ClubMembership> queryWrapper = membershipService.getQueryWrapper(userId, clubId);
        if (membershipService.count(queryWrapper) < 1) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户未加入此社团");
        }
        ClubMembership existMembership = membershipService.getOne(queryWrapper);
        if (!isDeleteClub && existMembership.getIdentity().equals(ClubMemberRoleEnum.MANAGER.getInfo())) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "社长无法直接退出");
        }

        QueryWrapper<ActivityMembership> activityMembershipQueryWrapper = new QueryWrapper<>();
        activityMembershipQueryWrapper.eq("userId", userId);
        List<Activity> activityListOfClub = activityService.getActivityListOfClub(clubId);
        List<Long> notEndActivityIdListOfClub = activityListOfClub.stream()
                .filter(activity -> {
                    if (activity.getStatus() < ActivityStatusEnum.END.getCode()) {
                        return true;
                    }
                    return false;
                })
                .map(Activity::getId)
                .collect(Collectors.toList());
        if (!notEndActivityIdListOfClub.isEmpty()) {
            activityMembershipQueryWrapper.in("activityId", notEndActivityIdListOfClub);
            if (activityMembershipService.count(activityMembershipQueryWrapper) > 0) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "用户参加了该社团未结束的活动，无法退出");
            }
        }
    }

    /**
     * 通过申请
     * @param request
     */
    @Override
    @Transactional
    public void acceptAddClub(AcceptApplicationRequest request) {
        //新增社团
        Club club=new Club();
        club.setClubName(request.getClubMessage().getClubName());
        club.setTags(request.getClubMessage().getClubTags());
        club.setUserId(request.getUserId());
        club.setIntroduction(request.getClubMessage().getClubIntroduction());
        if(this.baseMapper.insert(club)==0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加社团失败");
        }
        //修改申请状态为通过
        ClubApplication byId = applicationService.getById(request.getId());
        byId.setResult(ReviewResultEnum.ACCEPT.getCode());
        applicationService.updateById(byId);
    }

    @Override
    public Page<ListClubVO> getAllClub(PageQueryRequest page) {
        Page<Club> clubPage=new Page<Club>().setCurrent(page.getCurrent()).setSize(page.getPageSize());
        QueryWrapper<Club> queryWrapper = new QueryWrapper<>();
        if(page.getQuery()!=null){
            queryWrapper.like("clubName",page.getQuery());
        }
        List<Club> clubs = this.baseMapper.selectList(clubPage, queryWrapper);
        clubPage.setRecords(clubs);
        return convertListClub(clubPage);
    }

    @Override
    public ClubTypeVO getClubType() {
        ClubTypeVO clubTypeVO = new ClubTypeVO();
        clubTypeVO.setAcademic(this.baseMapper.getClubType("%学术类%"));
        clubTypeVO.setArt(this.baseMapper.getClubType("%艺术类%"));
        clubTypeVO.setVolunteer(this.baseMapper.getClubType("%公益类%"));
        clubTypeVO.setCulture(this.baseMapper.getClubType("%文化类%"));
        clubTypeVO.setRecreation(this.baseMapper.getClubType("%娱乐类%"));
        clubTypeVO.setCareer(this.baseMapper.getClubType("%职业发展类%"));
        clubTypeVO.setOther(this.baseMapper.getClubType("%其他类%"));
        return clubTypeVO;
    }

    @Override
    public boolean deleteClubs(List<ClubDeleteRequest> clubs) {
        clubs.forEach(e->{
            Club club=new Club();
            club.setId(e.getClubId());
            club.setUserId(e.getUserId());
            this.deleteClub(club);
        });
        return true;
    }

    @Override
    public List<Activity> getActivityInClub(Long clubId) {
        QueryWrapper<Activity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clubId", clubId);
        return activityService.list(queryWrapper);
    }

    @Override
    public List<ClubAnnouncement> getClubAnnouncementList(Long clubId) {
        QueryWrapper<ClubAnnouncement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("clubId", clubId);
        return announcementService.getBaseMapper().selectList(queryWrapper);
    }

    private Page<ListClubVO> convertListClub(Page<Club> list){
        return new Page<ListClubVO>().setRecords(list.getRecords().stream().map(club -> {
            ListClubVO listClubVO = new ListClubVO();
            listClubVO.setId(club.getId());
            listClubVO.setClubName(club.getClubName());
            listClubVO.setUserName(userMapper.getClubManagerName(club.getUserId()));
            listClubVO.setTags(club.getTags());
            listClubVO.setIntroduction(club.getIntroduction());
            listClubVO.setMemberCount(club.getMemberCount());
            listClubVO.setCreateTime(club.getCreateTime());
            listClubVO.setUpdateTime(club.getUpdateTime());
            listClubVO.setIsDelete(club.getIsDelete());
            return listClubVO;
        }).toList()).setCurrent(list.getCurrent()).setSize(list.getSize()).setTotal(list.getTotal());
    }
}




